package com.wowangz.cms.systemmanage.channel.api;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.RandomLowerNumber;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.channel.dto.ChannelInfo;
import com.wowangz.cms.systemmanage.channel.dto.GoodsInfo;
import com.wowangz.cms.systemmanage.channel.entity.Channel;
import com.wowangz.cms.systemmanage.channel.entity.ChannelPrice;
import com.wowangz.cms.systemmanage.channel.service.ChannelService;

@Scope("prototype")
@Controller
public class ChannelController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(ChannelController.class);

	/**
	 * 点击菜单"商家优惠"显示“商家优惠”列表
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/channel/queryChannelInfoList.web")
	public String queryChannelInfoList(HttpServletRequest request, HttpServletResponse response, Model model) {		
		
		return "/WEB-INF/jsp/systemmanage/channel/channelInfoList";
	}

	/**
	 * 打开“商家优惠”列表加载列表数据
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/channel/queryChannelListInfoDataGrid.json")
	public void queryChannelListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());

			ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
			//UserService userService = (UserService) IssTransactionContainer.getInstance(UserService.class, false);		
			long resultCount = channelService.findResultCount(map);
			List<ChannelInfo> resultList = channelService.findResultList(map);
			/*for(ChannelInfo result : resultList){
				User user = userService.findUserById(result.getCreateUserId());
				if(user != null){
					result.setCreateUserName(user.getUsername());
				}	
			}*/		
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.STRING);
			dataStyle.addDepict("channelId", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("code", DataTypeConstant.STRING);
			dataStyle.addDepict("goodsName", DataTypeConstant.STRING);
			dataStyle.addDepict("costPrice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("preferentialPrice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("unit", DataTypeConstant.STRING);
			dataStyle.addDepict("createTime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("createUserName", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
			logger.info("加载商家优惠列表数据成功");
		} catch (Exception e) {
			logger.error("加载商家优惠列表数据失败",e);
			e.printStackTrace();
			logger.debug(e.getMessage());
		}
	}
	
	/**
	 * 跳转商家优惠新增页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/channel/toAddChannel.web")
	public String toAddParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("code", RandomLowerNumber.randomStr(8));
		return "/WEB-INF/jsp/systemmanage/channel/channelInfoAdd";
	}
	
	/**
	 * 验证商家优惠（不允许重复的name和code）
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/channel/validationChannel.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validationParameter(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Channel channel = null;
		ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
		try {
			HashMap<String, Object> map = new HashMap<String, Object>();
			channel = (Channel) ServletUtils.getParametersToBaseEntity(request, Channel.class);

			if (null != channel.getId()) {
				map.put("id", channel.getId());
			}
			map.put("code", channel.getCode());
			map.put("name", channel.getName());
			if (!channelService.validationChannel(map)) {
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.channle.channleExsit"));
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, getUserContext()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增商家优惠
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/channel/addChannel.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		Channel channel = null;
		ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, true);
		try {
			channel = (Channel) ServletUtils.getParametersToBaseEntity(request, Channel.class);			
			String idss = request.getParameter("ids");
			String preferentialPricess = request.getParameter("gatheramounts");
			String[] ids = idss.split(",");
			String[] preferentialPrices = preferentialPricess.split(",");	
			if(preferentialPrices==null || preferentialPrices.length == 0){
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "systemmanage.channle.alert3"));
			}else{
				channelService.addChannelInfo(channel,ids,preferentialPrices,String.valueOf(getUserContext().getLoginUser().getId()));			
				logger.info("新增商家[{}]优惠成功", channel.getId());
				getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
				getUserContext().setCloseWindow(true);
			}			
		} catch (Exception e) {
			logger.error("新增商家[{}]优惠失败", channel.getId(),e);
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/systemmanage/channel/channelInfoList";
	}
	
	/**
	 * 进入商家优惠修改
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/channel/toUpdateChannel.web")
	public String toUpdateChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String id = getRequest().getParameter("id");
			ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
			ChannelInfo channelInfo = channelService.findChannelInfoById(id);
			model.addAttribute("channelInfo", channelInfo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/channel/channelInfoUpdate";
	}

	/**
	 * 修改商家优惠
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmanage/parameter/updateChannel.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
		String id = request.getParameter("id");
		ChannelPrice channelPrice = (ChannelPrice) ServletUtils.getParametersToBaseEntity(request, ChannelPrice.class);
		try {
			if (StringUtils.isNotEmpty(id)) {
				channelPrice.setModifyUserId(String.valueOf(getUserContext().getLoginUser().getId()));
				channelPrice.setModifyTime(new Date());
				channelService.updateChannelPrice(channelPrice);
				logger.info("修改商家[{}]优惠成功", channelPrice.getChannelId());
				getUserContext().setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
				getUserContext().setCloseWindow(true);
			}
		} catch (Exception e) {
			logger.error("修改商家[{}]优惠失败", channelPrice.getChannelId(),e);
			e.printStackTrace();
			getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/systemmanage/channel/channelInfoList";
	}
	
	/**
	 * 删除商家优惠信息
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmanage/channel/deleteChannel.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Channel channel = new Channel();
		try {
			String channelId = getRequest().getParameter("channelid");			
			channel.setId(channelId);
			channel.setDataStatus("BlockUp");
			channel.setCreateTime(new Date());
			channelService.updateChannel(channel);
			logger.info("删除商家[{}]优惠成功", channel.getId());
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			logger.error("删除商家[{}]优惠失败", channel.getId(),e);
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}

	
	/**
	 * 打开“商品信息”列表加载列表数据
	 * 
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmanage/channel/queryGoodsInfoDataGrid.json")
	public void queryGoodsInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());

			ChannelService channelService = (ChannelService) IssTransactionContainer.getInstance(ChannelService.class, false);
			long resultCount = channelService.findGoodsResultCount(map);
			List<GoodsInfo> resultList = channelService.findGoodsResultList(map);
			for(GoodsInfo result:resultList){ 
				result.setPreferentialPrice(0.00);
		    }  
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.STRING);
			dataStyle.addDepict("goodsName", DataTypeConstant.STRING);
			dataStyle.addDepict("costPrice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("preferentialPrice", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("unit", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, getUserContext()));
			}
			logger.info("加载商品信息列表数据成功");
		} catch (Exception e) {
			logger.error("加载商品信息列表数据失败",e);
			e.printStackTrace();
			logger.debug(e.getMessage());
		}
	}
	
	

}
